<?php require_once(dirname(__FILE__) . '/../include/config.inc.php');
require_once "function.php";

/*
进度：
0 已经撤单
1 报修成功
2 客服已经联系
3 系统已经派单
4 工程师接单
5 维修完成
6 已经评价
*/

$uid = $_SESSION['id'];
$userInfo = "";
if (isset($uid)) {

    //有session 从数据库中读取用户名信息
    //$openid_str=$_SESSION['openid'];
    $sql = "SELECT u.*,g.groupname  as groupname  FROM `#@__user` as u 
				   left join `#@__usergroup` as g  on u.level=g.id  
				   WHERE u.id='$uid' ";
    $row = $dosql->GetOne($sql);
    if (is_array($row) && isset($row['id'])) {
        // 返回用户 id
        $id = $row['id'];
        $_SESSION['id'] = $id;
        $userInfo = $row;
        $level = intval($row['level']);
    }
}

if ($level > 4) {
    exit();
}


$orderid = empty($orderid) ? "" : intval($orderid);
if (isset($orderid)) {

    // 拉取用户信息
    $row = $dosql->GetOne("SELECT * FROM `#@__order`   WHERE  id='$orderid'   AND is_delete=0 ");
    if (is_array($row) && isset($row['id'])) {
        // 返回工单数据
        /*
        进度：
        0 已经撤单
        1 报修成功
        2 客服已经联系
        3 系统已经派单
        4 工程师接单
        5 维修完成
        6 已经评价
        */
        if ($row['qiandao'] == '') {
            echo "<script>alert('请先签到！')</script>";
            exit();

        }


        $user_openid = $row['openid'];
        $jindu2 = $row['jindu'];
        $apply_type = $row['apply_type'];
        $apply_device = $row['apply_device'];

        $zhixingren = "";

        $mids = $row['manageid'];
        $fee = $row['fee'];

        //故障图片

        $pic_lists = "";
        $previewImage_url = array();
        if (!empty($row['picfiles'])) {
            $pic_lists = '<ul class="weui-uploader__files" id="uploaderFiles">';

            $picurl_arr = json_decode($row['picfiles'], true);
            for ($i = 0; $i < count($picurl_arr); $i++) {
                $previewImage_url[] = $picurl_arr[$i];
                $pic_lists .= '<li class="weui-uploader__file" style="background-image:url(' . $picurl_arr[$i] . ')"><img src="' . $picurl_arr[$i] . '" width="0"/></li>';
            }
        }
    } else {
        echo "<script>alert('任务不存在或者已经删除！')</script>";
        exit();
    }
}
?>
    <!DOCTYPE html>
    <html>
    <head>
        <title><?php echo $cfg_webname; ?> </title>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
        <meta name="description" content="<?php echo $cfg_webname; ?>">
        <link rel="stylesheet" href="lib/weui.min.css">
        <link rel="stylesheet" href="css/jquery-weui.css">
        <link rel="stylesheet" href="css/font-awesome.min.css">
        <link rel="stylesheet" href="css/demos.css">
        <link rel="stylesheet" href="/admin/ui/css/bootstrap.min.css">
        <link rel="stylesheet" href="/admin/ui/css/bootstrap-theme.min.css">
    </head>
    <style>
        .weui-input { width: 150px; text-align: right;border: solid 1px #fff !important;}
    </style>
<body ontouchstart>
    <div class="top">
        <div class="user_top">
            <i>
                <?php
                if (intval($level) > 1) {
                    echo '<a href="manage.php">' . $userInfo['groupname'] . '</a>';
                } else {
                    echo $userInfo['groupname'];
                } ?>
            </i>
            <div class="user_top_conn"><img src="<?php echo $userInfo['headimgurl'] ?>"/>
                <p><?php echo $userInfo['truename'] ?></p>
                <?php if (intval($level) > 1) { ?><a class="user_link" href="member.php">返回用户</a><?php } ?>
            </div>
        </div>
    </div>
    <!--工单列表开始-->

    <!--工单详情开始-->
    <!--工单详情开始-->
    <div class="main">
        <div class="weui-cells__title"><i class="fa fa-id-card-o" aria-hidden="true"></i>工单信息</div>
        <div class="weui-form-preview">
            <div class="weui-form-preview__bd">
                <div class="weui-form-preview__item">
                    <label class="weui-form-preview__label">工单号：</label>
                    <span class="weui-form-preview__value">
		<?php
        if (!empty($row['poster'])) {
            echo '<i class="fa fa-smile-o blue "></i>';
        }
        if (!empty($row['openid'])) {
            echo '<i class="fa fa-weixin green"></i>';
        }
        ?>
        <?php echo date("Ymd", $row['post_time']) . "-" . $row['id'] ?>
        </span>
                </div>
                <div class="weui-form-preview__item">
                    <label class="weui-form-preview__label">单位：</label>
                    <span class="weui-form-preview__value"><?php echo $row['school'] ?></span></div>
                <?php if (!empty($row['truename'])) { ?>
                    <div class="weui-form-preview__item">
                        <label class="weui-form-preview__label">联系人：</label>
                        <span class="weui-form-preview__value"><?php echo $row['truename'] ?></span></div>
                <?php } ?>
                <?php if (!empty($row['mobile'])) { ?>
                    <div class="weui-form-preview__item">
                        <label class="weui-form-preview__label">电话：</label>
                        <span class="weui-form-preview__value"><a href="tel:<?php echo $row['mobile'] ?>"><i class="fa fa-mobile"><?php echo $row['mobile'] ?></a></i></span>
                    </div>
                <?php } ?>
                <?php if (!empty($row['mobile'])) { ?>
                    <div class="weui-form-preview__item">
                        <label class="weui-form-preview__label">地址：</label>
                        <span class="weui-form-preview__value" id="daohang" data-orderid="<?php echo $row['id'] ?>"><i class="fa fa-map-marker"><?php echo $row['address'] ?></i></span>
                    </div>
                <?php } ?>
                <div class="weui-form-preview__item">
                    <label class="weui-form-preview__label">服务类型：</label>
                    <span class="weui-form-preview__value"><i class="fa  fa-drivers-license-o red"></i> <?php echo getRepairMode($row['apply_device']) ?></span>
                </div>

                <div class="weui-form-preview__item">
                    <label class="weui-form-preview__label">描述：</label>
                    <span class="weui-form-preview__value"><?php echo $row['content'] ?></span></div>
                <div class="weui-form-preview__item">
                    <label class="weui-form-preview__label">执行人：</label>
                    <span class="weui-form-preview__value">
			<?php
            if (!empty($row['manageid'])) {
                $m_str = $row['manageid'];
                $m_arr = explode(",", $m_str);
                foreach ($m_arr as $key => $val) {
                    echo ' <i class="fa  fa-user-o red"></i>      ' . getManage($val);
                    $zhixingren .= getManage($val) . "    ";
                }
            }
            ?>

        </span></div>
                <div class="weui-form-preview__item">
                    <label class="weui-form-preview__label">任务时间：</label>
                    <span class="weui-form-preview__value"><i class="fa fa-play green"></i> <?php echo date("Y-m-d H:i:s", $row['begintime']) . "  
		<br/><i  class=' red fa  fa-stop'></i>     " . date("Y-m-d H:i:s", $row['endtime']) ?></span></div>

                <div class="weui-form-preview__item">
                    <label class="weui-form-preview__label">故障图片</label>
                    <div class="weui-uploader">
                        <div class="weui-uploader__bd">
                            <ul class="weui-uploader__files" id="uploaderFiles_apply">
                                <?php echo $pic_lists; ?>
                            </ul>
                        </div>
                    </div>
                </div>
                <div class="weui-form-preview__item">
                    <label class="weui-form-preview__label red">维修进度</label>
                    <span class="weui-form-preview__value">
        <ul>
          <?php
          $dosql->Execute("SELECT * FROM `#@__order_log` WHERE orderid='$orderid'  ORDER BY id asc");
          while ($row2 = $dosql->GetArray()) {
              ?>
              <li><i class="fa fa-check-circle"><?php echo $row2['op'] ?></i> <?php echo date("m-d H:i:s", $row2['op_time']) ?></li>
              <?php
          }
          ?>
        </ul>
        </span></div>
                <div class="sub_btn"></div>
                <input type="hidden" name="manageid" id="manageid" value="<?php echo $uid; ?>">
            </div>
        </div>

    </div>
    <!--工单详情结束-->
<?php if ($jindu2 == '4') { ?>
<div class="main">
    <div class="weui-cells__title"><i class="fa fa-id-card-o" aria-hidden="true"></i> 工单完修申报</div>
    <!--完修模块-->
    <form name="form" id="form" method="post" action="">
        <input type="hidden" id="latitude" name="latitude">
        <input type="hidden" id="longitude" name="longitude">
        <input type="hidden" id="accuracy" name="accuracy">
        <input type="hidden" id="address" name="address">
        <input type="hidden" id="address_name" name="address_name" value="">
        <div class="weui-cells weui-cells_form">
            <div class="weui-cells__title">服务详情：</div>
            <div class="weui-cells ">
                <div class="weui-cell">
                    <div class="weui-cell__bd">
                        <textarea class="form-control" name="content" id="content" placeholder="请输入文本" rows="3"></textarea>
                        <div class="weui-textarea-counter"><span>0</span>/200</div>
                    </div>
                </div>
            </div>
        </div>
        <!--上传 开始-->
        <div class="weui-cell">
            <div class="weui-cell__bd">
                <div class="weui-uploader">
                    <div class="weui-uploader__hd">
                        <p class="weui-uploader__title">图片上传</p>
                        <div class="weui-uploader__info">0/9</div>
                    </div>

                    <div class="weui-uploader__bd">
                        <ul class="weui-uploader__files" id="uploaderFiles">

                        </ul>
                        <div class="weui-uploader__input-box">
                            <input id="uploaderInput" class="weui-uploader__input">
                            <input type="hidden" name="picurls" id="picurls">
                            <input type="hidden" name="picfiles" id="picfiles">
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <!--上传 结束-->
        <input type="hidden" name="action" id="action" value="add"/>

    </form>
    <!-- 完修模块-->

    <div class="sub_btn">
        <a href="javascript:;" class="weui-btn weui-btn_primary" id="over_btn" onclick="cfm_order();return false;">确认完修</a>
    </div>
<?php } ?>
    <div class="clear"></div>
</div>

    <div class="clear"></div>
    <div class="sub_btn"></div>
    <script src="lib/jquery-2.1.4.js"></script>
    <script src="lib/fastclick.js"></script>
    <script src="js/jquery-weui.js"></script>
    <script src="https://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script>
    <script>
        $(function () {
            FastClick.attach(document.body);
        });

        //提交表单
        function cfm_order() {
            if ($("#content").val() == "") {
                $.toast("请输入维修详情", "forbidden");
                $("#content").focus();
                return false;
            }
            if ($("#picurls").val() == "") {
                $.toast("完修图片必须上传", "forbidden");
                return false;
            }

            $("#form").submit();

        }

        wx.config({
            debug: false,
            appId: '<?php echo $signPackage["appId"];?>',
            timestamp: <?php echo $signPackage["timestamp"];?>,
            nonceStr: '<?php echo $signPackage["nonceStr"];?>',
            signature: '<?php echo $signPackage["signature"];?>',
            jsApiList: [
                // 所有要调用的 API 都要加到这个列表中
                'onMenuShareTimeline',
                'onMenuShareAppMessage',
                'onMenuShareQQ',
                'onMenuShareWeibo',
                'openAddress',
                'chooseImage',
                'previewImage',
                'uploadImage',
                'downloadImage'
            ]
        });
        wx.ready(function () {
            //预览图片
            var apply_images = $("#uploaderFiles_apply").find("img");
            var imgPaths = [];
            apply_images.each(function () {
                imgPaths.push(this.src);
            });
            $("#uploaderFiles_apply").on("click", function () {
                current = imgPaths[0];
                wx.previewImage({
                    current: current,
                    urls: imgPaths
                });
            });

            //获取定位

            //地址
            wx.getLocation({
                type: 'gcj02', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
                success: function (res) {
                    var latitude = res.latitude; // 纬度，浮点数，范围为90 ~ -90
                    $("#latitude").val(latitude);
                    var longitude = res.longitude; // 经度，浮点数，范围为180 ~ -180。
                    $("#longitude").val(longitude);
                    var speed = res.speed; // 速度，以米/每秒计
                    var accuracy = res.accuracy; // 位置精度
                    $("#accuracy").val(accuracy);
                    if (latitude != '0.0') {
                        $.ajax({
                            url: "getMap.php?l=" + latitude + "&w=" + longitude,
                            type: "GET",
                            timeout: 2000,
                            dataType: "json",
                            success: function (data) {
                                console.log('ok');
                                var gps_address = data.result.address;
                                var address_name = data.result.formatted_addresses.recommend;
                                //alert(gps_address);
                                $("#address").val(gps_address);
                                $("#address_name").val(address_name);
                            },
                            error: function (data) {
                                console.log('error');

                            }
                        });
                    } else {
                        $.alert("请把gps开启为当前地点", " 温馨提示");
                    }
                },
                cancel: function (res) {
                    $.alert("你拒绝授权获取地理位置，我们的工程师无法快速定位。时效性可能会延时，请谅解", " 温馨提示");
                }

            });
            //打开相册
            var images = {
                localId: [],
                serverId: []
            };
            var filepaths = [];
            document.querySelector('#uploaderInput').onclick = function () {
                wx.chooseImage({
                    sourceType: ['camera'], // 可以指定来源是相册还是相机，默认二者都有
                    success: function (res) {
                        images.localId = res.localIds;
                        var picurls = res.localIds;
                        var pic_count = res.localIds.length;
                        $(".weui-uploader__info").html('已选择 ' + pic_count + ' 张图片');
                        $("#picurls").val(picurls);
                        //批量上传
                        for (var i = 0; i < pic_count; i++) {
                            wx.uploadImage({
                                localId: picurls[i], // 需要上传的图片的本地ID，由chooseImage接口获得
                                isShowProgressTips: 1, // 默认为1，显示进度提示
                                success: function (res) {
                                    var serverId = res.serverId; // 返回图片的服务器端ID
                                    console.log(serverId);
                                    $.ajax({
                                        type: 'POST',
                                        url: "getFile.php",
                                        data: {serverId: serverId},
                                        dataType: 'JSON',
                                        success: function (result) {
                                            if (result.errno == 0) {
                                                console.log(result.msg);
                                                if (result.msg === "ok") {
                                                    filepaths.push(result.filename);
                                                    $("#picfiles").val(filepaths);
                                                    $("#uploaderFiles").append('<li class="weui-uploader__file" style="background-image:url(' + result.filename + ')"></li>');
                                                } else {
                                                    $.alert("上传失败<br/> 请联系管理员！", "温馨提示");
                                                }
                                            }
                                        }
                                    });
                                }
                            });
                        }
                        $("#picfiles").val(filepaths);
                        //批量上传
                    }
                });


            }

        })


    </script>


<?php
//工单提交处理

if (isset($action) and $action == 'add') {
    if (empty($content) or empty($picfiles)) {
        echo '<script type="text/javascript">
	$.toast("请填写完修概要或者上传图片", function() {
		 
		});
	</script>';
        exit();
    }

    //查询 最新的进度状态
    $k = $dosql->GetOne("select jindu from `#@__order` where id='$orderid'");
    if (is_array($k) && isset($k['jindu'])) {
        if ($k['jindu'] == '5') {
            echo '<script type="text/javascript">
			$("#over_btn").hide();
			$.toast("不要重复申报", function() {
				 window.location.href="morder.php";
				});
			</script>';
            exit();
        }
    } else {
        echo '<script type="text/javascript">
			$("#over_btn").hide();
			$.toast("申报的单号不正确", function() {
				 window.location.href="morder.php";
				});
			</script>';
        exit();
    }


    $content = htmlspecialchars($content);
    $picurls = "";
    $jindu = "5";
    $post_time = time();
    $post_time2 = date("Y-m-d H:i:s", time());


    $picfiles_str="";
    if($picfiles!=""){
        $picfiles_arr=explode(",",$picfiles);
        $picfiles_str=json_encode($picfiles_arr);

    }


    //更新工单
    $sql2 = "update `#@__order` set over_remark='$content',over_picurls='$picfiles_str',over_time='$post_time',jindu='5',latitude2='$latitude',longitude2='$longitude',accuracy2='$accuracy'  where id='$orderid ' ";
    $dosql->ExecNoneQuery($sql2);




    //增加 任务奖励
    $m2_arr = explode(",", $mids);
    foreach ($m2_arr as $key => $val) {
        //增加奖励计划
        $dosql->ExecNoneQuery("update  `#@__user` set fee=fee+'$fee' where id='$val' ");
        //写入 奖励操作记录
        $dosql->ExecNoneQuery("insert into `#@__fee_log`(orderid,op,op_time,jindu,manageid,remark,fee,task) values ('$orderid','add','$post_time','5','$val','完成任务 获得奖励','$fee','$apply_device')");
    }
    $op_name = getTypeName($apply_type) . "已送达";
    if ($apply_type == '1' || $apply_type == '2' || $apply_type == '3' ) {
        $op_name = getTypeName($apply_type) . "已完成";
    }


    //插入更新的状态
    $dosql->ExecNoneQuery("insert into `#@__order_log`(orderid,op,op_time,jindu,manageid,latitude,longitude,accuracy,address,address_name,picurls,op_manageid) values ('$orderid','$op_name','$post_time','5','$uid','$latitude','$longitude','$accuracy','$address','$address_name','$picfiles_str','$uid')");
    $orderidname = date('Ymd', time()) . "-" . $orderid;
    //封装为json格式的数据
    $repairname = getRepairMode($apply_device);
    $json = '{
	  "touser": "' . $user_openid . '" ,  
	  "template_id": "' . $cfg_order_status . '",    
	  "url":"' . $cfg_weburl . 'wx/orderDetail.php?orderid=' . $orderid . '",         
	  "data": {
		  "first": {
			  "value": "您好，' . $op_name . '，请对我们的服务进行评价", 
			  "color": "#f71b03"
		  }, 
			  "keyword1": {
				  "value": "' . $orderidname . '", 
				  "color": "#173177"
			  }, 
			  "keyword2": {
				  "value": "' . $post_time2 . '", 
				  "color": "#173177"
			  },
			  "keyword3": {
				  "value": "' . $zhixingren . '", 
				  "color": "#0e48cb"
			  },
			  "keyword4": {
				  "value": " ' . $repairname . '", 
				  "color": "#173177"
			  },
			  "keyword5": {
				  "value": "' . $op_name . '", 
				  "color": "#173177"
			  },
			  "remark": {
				  "value": "百分服务，满意100；请您在百忙中对我们的服务进行评价。服务热线："' . $cfg_hotline . '",  
				  "color": "#f71b03"
			  } 
	  }
	}';
    sendWxMsg($json);


    echo '<script type="text/javascript">
	$("#over_btn").hide();
	$.toast("完修申报成功", function() {
		 window.location.href="morder.php";
		});
	</script>';
    exit();

}

?>


<?php require_once('footer.php'); ?>
